<template>
  <div class="custom">
    <header>
      <el-button :icon="Plus" type="primary" @click="clickAdd">添加分类</el-button>
      <el-input v-model="searchkey" style="width: 300px" placeholder="请输入类目名称搜索" clearable @change="getList">
        <template #prefix>
          <el-icon class="el-input__icon"><search /></el-icon>
        </template>
      </el-input>
    </header>

    <el-table :data="tableData" style="width: 100%; margin-bottom: 20px" row-key="categoryId" border :default-expand-all="false">
      <el-table-column prop="name" label="分类名称" width="200" />
      <el-table-column prop="preview" label="分类预览" :align="'center'" :header-align="'center'" />
      <el-table-column prop="createTime" label="创建时间" :align="'center'" :header-align="'center'" />
      <el-table-column prop="productNum" label="商品数" :align="'center'" :header-align="'center'" />
      <el-table-column prop="sortOrder" label="排序" :align="'center'" :header-align="'center'">
        <template #default="scope">
          <el-input v-model="scope.row.sortOrder" type="number" min="1" @change="debounceChangeSort(scope.row, $event)" />
        </template>
      </el-table-column>
      <el-table-column label="分类icon" :align="'center'" :header-align="'center'">
        <template #default="scope">
          <el-image
            v-if="scope.row.image"
            :src="scope.row.image"
            :preview-src-list="[scope.row.image]"
            :z-index="9999"
            preview-teleported
            fit="cover"
            style="width: 80px; height: 80px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" :align="'center'" :header-align="'center'">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 1">显示</el-tag>
          <el-tag v-else type="info">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="actin" label="操作" width="160" :align="'center'" :header-align="'center'">
        <template #default="scope">
          <div class="btn-wrap">
            <el-button
              v-if="scope.row.fomart ? scope.row.fomart.split('-').length !== 3 : false"
              :type="'primary'"
              link
              @click="clickAdd(scope.row)"
            >
              添加
            </el-button>
            <el-button :type="'primary'" link @click="clickEidt(scope.row)">编辑</el-button>
            <el-button :type="'primary'" link @click="clickDel(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 添加/编辑分类 -->
  <ClassifyFormDialog
    ref="classifyFormDialogRef"
    :optionInfo="optionInfo"
    @close="classifyFormDialogClose"
    @submit="classifyFormDialogSubmit"
  ></ClassifyFormDialog>

  <!-- 删除分类时的提示框 -->
  <el-dialog v-model="dialogDelVisible" title="提示" width="800" modal-class="del-dialog" align-center>
    <template v-if="isAllowDel">
      <div class="title">
        <p>{{ delCuurent.name }}</p>
      </div>
      <b>删除该分类后会同步删除子级分类，是否继续？</b>
      <p style="margin-top: 20px">商品数量：0</p>
      <p>下级分类数量：0</p>
    </template>

    <template v-else>
      <img src="@/assets/images/products/error.png" class="error" alt="" />

      <div class="title">
        <p>{{ delCuurent.name }}</p>
      </div>
      <b>该类目下已经关联了商品数据，无法删除！</b>
      <b>请将分类里存在的商品转移至其它类目后再进行删除！</b>
      <p style="margin-top: 20px">
        商品数量：
        <template v-for="(item, index) in productsList" :key="item.categoryId">
          <i v-if="index !== productsList.length - 1" :style="{ color: item.productNum > 0 ? '#ff3333' : '' }">
            {{ item.name }}（{{ item.productNum }}）、
          </i>
          <i v-else :style="{ color: item.productNum > 0 ? '#ff3333' : '' }">{{ item.name }}（{{ item.productNum }}）</i>
        </template>
      </p>
      <p>
        下级分类数量：<i :style="{ color: productsList.length > 0 ? '#ff3333' : '' }">{{ productsList.length }}</i>
      </p>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <template v-if="isAllowDel">
          <el-button @click="dialogDelVisible = false">取消</el-button>
          <el-button type="primary" @click="submitDel">确认</el-button>
        </template>
        <template v-else>
          <el-button type="primary" @click="dialogDelVisible = false">我知道了</el-button>
        </template>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from "vue";
import { Plus, Search } from "@element-plus/icons-vue";
import ClassifyFormDialog from "./ClassifyFormDialog";
import { addLevel1, deleteCategory, saveJuniorCategory, saveCurrentOrJuniorCategory } from "@/api/products/classify";
import useClassifyStore from "@/store/modules/classify";
const classifyStore = useClassifyStore();
import { ElMessage } from "element-plus";
import { _throttle } from "@/utils/index";

const dialogDelVisible = ref(false); //删除操作时的提示框
const isAllowDel = ref(true); //是否允许删除操作（分类下没有商品可以删除，有商品时不可以删除）
const searchkey = ref("");
const tableData = ref([
  {
    id: 1,
    date: "2016-05-02",
    name: "wangxiaohu",
    address: "No. 189, Grove St, Los Angeles",
    sort: 1,
    level: 1
  },
  {
    id: 2,
    date: "2016-05-04",
    name: "wangxiaohu",
    address: "No. 189, Grove St, Los Angeles",
    sort: 1,
    level: 1
  },
  {
    id: 3,
    date: "2016-05-01",
    name: "wangxiaohu",
    address: "No. 189, Grove St, Los Angeles",
    sort: 1,
    level: 1,
    children: [
      {
        id: 31,
        date: "2016-05-01",
        name: "wangxiaohu",
        address: "No. 189, Grove St, Los Angeles",
        sort: 1,
        level: 2,
        children: [
          {
            id: 41,
            date: "2016-05-01",
            name: "aaaaaa",
            address: "aaaaaa",
            sort: 1,
            level: 3
          },
          {
            id: 42,
            date: "2016-05-01",
            name: "bbbbbb",
            address: "bbbbbb",
            sort: 1,
            level: 3
          }
        ]
      },
      {
        id: 32,
        date: "2016-05-01",
        name: "wangxiaohu",
        address: "No. 189, Grove St, Los Angeles",
        sort: 1,
        level: 2
      }
    ]
  },
  {
    id: 4,
    date: "2016-05-03",
    name: "wangxiaohu",
    address: "No. 189, Grove St, Los Angeles",
    sort: 1,
    level: 1
  }
]);
const classifyFormDialogRef = ref();
const optionInfo = ref({
  isShow: false,
  type: "add",
  formData: {},
  list: []
});
// 查询list
const getList = async () => {
  const List = await classifyStore.getList({ searchkey: searchkey.value });
  tableData.value = List;
};
getList();

//点击添加
const clickAdd = item => {
  optionInfo.value.isShow = true;
  optionInfo.value.type = "add";
  optionInfo.value.formData = { ...item };
  optionInfo.value.list = tableData.value;
};
//点击编辑
const editCurrent = ref(null);
const clickEidt = item => {
  editCurrent.value = item;
  optionInfo.value.isShow = true;
  optionInfo.value.type = "edit";
  optionInfo.value.formData = { ...item };
  optionInfo.value.list = tableData.value;
};

const productsList = ref([]); //不能正常删除时，商品数列表信息
//点击删除
const delCuurent = ref(null);
const clickDel = item => {
  delCuurent.value = item;
  console.log("要删除的节点", item);
  dialogDelVisible.value = true;
  if (item.productNum === 0) {
    isAllowDel.value = true; //允许正常删除
  } else {
    isAllowDel.value = false; //不能正常删除
    productsList.value = item.children;
  }
};
//确认删除
const submitDel = () => {
  dialogDelVisible.value = false;
  console.log("删除这个分类===", delCuurent);
  deleteCategory({ categoryId: delCuurent.value.categoryId }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "删除成功",
        type: "success"
      });
      getList();
    }
  });
};
const debounceChangeSort = _throttle((item, event) => {
  const params = {
    ...item,
    sortOrder: event
  };
  saveCurrentOrJuniorCategory(params).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "排序修改成功",
        type: "success"
      });
      getList();
    }
  });
}, 3000);

const classifyFormDialogClose = () => {
  optionInfo.value.isShow = false;
};
//确认添加、编辑，组件的submit回调
const classifyFormDialogSubmit = (form, type, level) => {
  optionInfo.value.isShow = false;
  const formData = JSON.parse(JSON.stringify(form));
  if (formData.image && formData.image.length > 0) {
    formData.image = formData.image[0].fileUrl;
  } else {
    formData.image = "";
  }
  console.log("这是组件传递过来的form数据", formData, type, level);
  if (type === "add") {
    addFunction(formData, type, level);
  } else if (type === "edit") {
    editFunction(formData, type, level);
  }
};

const addFunction = (formData, type, level) => {
  if (level === 1) {
    //添加一级分类
    const params = {
      name: formData.name,
      remark: formData.tips,
      status: formData.status,
      sortOrder: Number(formData.sort)
    };
    addLevel1(params).then(res => {
      if (res.code === 200) {
        getList();
      }
    });
  } else if (level === 2) {
    //添加二级分类
    const list = formData.level2.map(item => {
      return {
        name: item.name,
        sortOrder: Number(item.sort),
        status: formData.status,
        image: item?.image[0]?.fileUrl
      };
    });
    const params = {
      categoryId: formData.level1,
      list
    };
    saveJuniorCategory(params).then(res => {
      console.log("添加二级分类成功===", res);
      if (res.code === 200) {
        getList();
      }
    });
  } else if (level === 3) {
    //添加三级分类
    const list = formData.level3.map(item => {
      return {
        name: item.name,
        sortOrder: Number(item.sort),
        status: formData.status,
        image: item?.image[0]?.fileUrl
      };
    });
    const params = {
      categoryId: formData.level2,
      list
    };
    saveJuniorCategory(params).then(res => {
      console.log("添加三级分类成功===", res);
      if (res.code === 200) {
        getList();
      }
    });
  }
};
const editFunction = (formData, type, level) => {
  let params = {};
  if (level === 1) {
    params = {
      ...editCurrent.value,
      name: formData.name,
      sortOrder: formData.sort,
      status: formData.status,
      image: formData.image,
      remark: formData.tips
    };
    console.log("这是编辑一级分类===11111", params, formData);
  } else if (level === 2) {
    params = {
      ...editCurrent.value,
      name: formData.level2[0].name,
      sortOrder: formData.level2[0].sort,
      status: formData.status,
      delFlag: formData.level2[0].delFlag,
      image: formData.level2[0]?.image[0]?.fileUrl || ""
    };
  } else if (level === 3) {
    params = {
      ...editCurrent.value,
      name: formData.level3[0].name,
      sortOrder: formData.level3[0].sort,
      status: formData.status,
      delFlag: formData.level3[0].delFlag,
      image: formData.level3[0]?.image[0]?.fileUrl || ""
    };
  }
  saveCurrentOrJuniorCategory(params).then(res => {
    if (res.code === 200) {
      getList();
    }
  });
};
</script>

<style lang="scss">
.del-dialog {
  .el-dialog__body {
    text-align: center;
    .error {
      width: 50px;
      height: 50px;
      vertical-align: bottom;
      margin-bottom: 30px;
    }
    .title {
      width: 200px;
      height: 60px;
      margin: 0 auto;
      border: 1px solid #dcdfe6;
      margin-bottom: 24px;
      p {
        font-size: 18px;
        line-height: 60px;
        color: #3d3d3d;
        font-weight: bolder;
      }
    }
    b {
      display: block;
      line-height: 24px;
    }
    i {
      font-style: normal;
    }
    p {
      color: #86909c;
      &:not(:last-of-type) {
        margin-bottom: 10px;
      }
      i {
        color: #4e5969;
      }
    }
  }
}
</style>
<style lang="scss" scoped>
h1,
p {
  padding: 0;
  margin: 0;
}
.custom {
  header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
  }
}
.btn-wrap {
  display: flex;
  justify-content: flex-end;
}
</style>
